package com.cetc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.cetc.common.util.JWTUtils;
import com.cetc.common.util.R;
import com.cetc.common.util.RedisUtil;
import com.cetc.entity.User;
import com.cetc.mapper.UserMapper;
import com.cetc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Map<String, Object> login(User user) {
        Map<String,Object> reMap = new HashMap<>();

        Wrapper<User> wrapper = new EntityWrapper();
        wrapper.eq("username",user.getUsername());
        wrapper.eq("password",user.getPassword());

        List<User> user1 = userMapper.selectList(wrapper);

        if(CollectionUtil.isNotEmpty(user1)){
            String token = JWTUtils.getToken(user1.get(0));

            setRedisToken(token,user1.get(0));

            reMap.put("token",token);
            reMap.put("msg",true);
            reMap.put("content","登陆成功");
        }else{
            reMap.put("msg",false);
            reMap.put("content","登陆失败，用户名或者密码不对 ");
        }

        return R.ok().put("data",reMap);
    }

    public void setRedisToken(String token,User user){
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getUseid());
        map.put("username",user.getUsername());

        redisUtil.set("token"+user.getUseid(),token);
        redisUtil.set(token,map);
    }
}
